import { Stream } from "stream";

//application/x-www-form-urlencoded;数据解析,这种类型不会出现文件
declare var Buffer:any;


if(module) module.exports = form_urlencoded;
export default function form_urlencoded (stream:Stream,MAX = 1024*1024*1024){
    // 限制数据量
    let size = 0;
    let par:any = {parameter:{},state:true}
    return new Promise((reserved,error)=>{
        let data = [];
        let end = ()=>{
            Buffer.from(Buffer.concat(data),'hex').toString().split("&").forEach((e:any)=>{
                e = e.split(/=/);
                par.parameter[e[0]]=e?.[1];
            })
            reserved(par)
        }
        let start = (a:Buffer)=>{
            data.push(a);
            size+=a.length;
            if(size>MAX){
                stream.removeListener("data",start)
                stream.removeListener("end",end)
                error(new Error("数据量超界"))
            }
        }
        stream.on("data",start)
        stream.on("end",end)
        stream.on("error",(err:Error)=>error(err))
    })
}